package com.ctw.tinyservices.id.core.segment.buffer;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author TongWei.Chen 2022/3/9 19:52
 *
 * 号段
 **/
public class Segment {
    /**
     * id值
     */
    private AtomicLong value = new AtomicLong(0L);

    /**
     * 最大id
     */
    private volatile long max;

    /**
     * 步长
     */
    private volatile int step;

    /**
     * 最小步长，用于动态步长
     */
    private volatile int minStep;

    /**
     * 最后一次更新时间，用于动态步长
     */
    private volatile long updateTimestamp;

    /**
     * 当前号段是否完成初始化
     */
    private volatile boolean isInit;

    /**
     * 获取当前号段剩余id数，也就是可用id数
     *
     * @return 剩余id数
     */
    public long getIdle() {
        return max - value.get();
    }

    public AtomicLong getValue() {
        return value;
    }

    public void setValue(AtomicLong value) {
        this.value = value;
    }

    public long getMax() {
        return max;
    }

    public void setMax(long max) {
        this.max = max;
    }

    public int getStep() {
        return step;
    }

    public void setStep(int step) {
        this.step = step;
    }

    public int getMinStep() {
        return minStep;
    }

    public void setMinStep(int minStep) {
        this.minStep = minStep;
    }

    public long getUpdateTimestamp() {
        return updateTimestamp;
    }

    public void setUpdateTimestamp(long updateTimestamp) {
        this.updateTimestamp = updateTimestamp;
    }

    public boolean isInit() {
        return isInit;
    }

    public void setInit(boolean init) {
        isInit = init;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Segment{");
        sb.append("value=").append(value);
        sb.append(", max=").append(max);
        sb.append(", step=").append(step);
        sb.append(", minStep=").append(minStep);
        sb.append(", updateTimestamp=").append(updateTimestamp);
        sb.append(", isInit=").append(isInit);
        sb.append('}');
        return sb.toString();
    }
}
